import { request } from "./index";
import type {
  ChatSession,
  ChatMessage,
  SendMessageRequest,
  PageResponse,
} from "@/types/chat";

// 聊天API接口
export const chatApi = {
  /**
   * 获取聊天会话列表
   */
  getSessions(page = 0, size = 20): Promise<ChatSession[]> {
    return request.get("/chat/sessions", { page, size });
  },

  /**
   * 创建新的聊天会话
   */
  createSession(data: {
    title?: string;
    personaId?: string;
    tags?: string[];
  }): Promise<ChatSession> {
    return request.post("/chat/sessions", data, {
      showLoading: true,
      loadingText: "创建会话中...",
    });
  },

  /**
   * 获取指定会话信息
   */
  getSession(sessionId: string): Promise<ChatSession> {
    return request.get(`/chat/sessions/${sessionId}`);
  },

  /**
   * 更新会话信息
   */
  updateSession(
    sessionId: string,
    data: {
      title?: string;
      personaId?: string;
      tags?: string[];
      archived?: boolean;
    },
  ): Promise<ChatSession> {
    return request.put(`/chat/sessions/${sessionId}`, data);
  },

  /**
   * 删除会话
   */
  deleteSession(sessionId: string): Promise<void> {
    return request.delete(
      `/chat/sessions/${sessionId}`,
      {},
      {
        showLoading: true,
        loadingText: "删除中...",
      },
    );
  },

  /**
   * 归档会话
   */
  archiveSession(sessionId: string): Promise<void> {
    return request.put(`/chat/sessions/${sessionId}/archive`);
  },

  /**
   * 取消归档会话
   */
  unarchiveSession(sessionId: string): Promise<void> {
    return request.put(`/chat/sessions/${sessionId}/unarchive`);
  },

  /**
   * 获取会话消息列表
   */
  getMessages(sessionId: string, page = 0, size = 50): Promise<ChatMessage[]> {
    return request.get(`/chat/sessions/${sessionId}/messages`, { page, size });
  },

  /**
   * 发送消息
   */
  sendMessage(data: SendMessageRequest): Promise<{
    userMessage: ChatMessage;
    assistantMessage?: ChatMessage;
  }> {
    const formData = new FormData();
    formData.append("sessionId", data.sessionId);
    formData.append("content", data.content);
    formData.append("type", data.type);

    if (data.personaId) {
      formData.append("personaId", data.personaId);
    }

    if (data.attachments) {
      data.attachments.forEach((file, index) => {
        formData.append(`attachments[${index}]`, file);
      });
    }

    return request.upload("/chat/messages", formData, {
      showLoading: false,
    });
  },

  /**
   * 重新生成消息
   */
  regenerateMessage(messageId: string): Promise<ChatMessage> {
    return request.post(
      `/chat/messages/${messageId}/regenerate`,
      {},
      {
        showLoading: true,
        loadingText: "重新生成中...",
      },
    );
  },

  /**
   * 编辑消息
   */
  editMessage(messageId: string, content: string): Promise<ChatMessage> {
    return request.put(`/chat/messages/${messageId}`, { content });
  },

  /**
   * 删除消息
   */
  deleteMessage(messageId: string): Promise<void> {
    return request.delete(`/chat/messages/${messageId}`);
  },

  /**
   * 点赞/点踩消息
   */
  rateMessage(
    messageId: string,
    rating: "like" | "dislike" | null,
  ): Promise<void> {
    return request.put(`/chat/messages/${messageId}/rating`, { rating });
  },

  /**
   * 收藏消息
   */
  favoriteMessage(messageId: string): Promise<void> {
    return request.post(`/chat/messages/${messageId}/favorite`);
  },

  /**
   * 取消收藏消息
   */
  unfavoriteMessage(messageId: string): Promise<void> {
    return request.delete(`/chat/messages/${messageId}/favorite`);
  },

  /**
   * 复制消息到其他会话
   */
  copyMessage(
    messageId: string,
    targetSessionId: string,
  ): Promise<ChatMessage> {
    return request.post(`/chat/messages/${messageId}/copy`, {
      targetSessionId,
    });
  },

  /**
   * 标记会话为已读
   */
  markAsRead(sessionId: string): Promise<void> {
    return request.put(`/chat/sessions/${sessionId}/read`);
  },

  /**
   * 搜索消息
   */
  searchMessages(
    query: string,
    options?: {
      sessionId?: string;
      personaId?: string;
      dateFrom?: string;
      dateTo?: string;
      messageType?: "text" | "image" | "file";
      page?: number;
      size?: number;
    },
  ): Promise<PageResponse<ChatMessage & { sessionTitle: string }>> {
    return request.get("/chat/search", {
      query,
      ...options,
    });
  },

  /**
   * 获取会话统计信息
   */
  getSessionStats(sessionId: string): Promise<{
    messageCount: number;
    tokensUsed: number;
    duration: number;
    personaChanges: number;
    averageResponseTime: number;
    userSatisfaction?: number;
  }> {
    return request.get(`/chat/sessions/${sessionId}/stats`);
  },

  /**
   * 导出会话
   */
  exportSession(
    sessionId: string,
    format: "json" | "txt" | "pdf" = "json",
  ): Promise<void> {
    return request.download(
      `/chat/sessions/${sessionId}/export`,
      { format },
      `session_${sessionId}.${format}`,
    );
  },

  /**
   * 分享会话
   */
  shareSession(
    sessionId: string,
    options: {
      includeSystemMessages?: boolean;
      expiresAt?: string;
      password?: string;
    },
  ): Promise<{
    shareId: string;
    shareUrl: string;
    expiresAt?: string;
  }> {
    return request.post(`/chat/sessions/${sessionId}/share`, options);
  },

  /**
   * 获取分享的会话
   */
  getSharedSession(
    shareId: string,
    password?: string,
  ): Promise<{
    session: ChatSession;
    messages: ChatMessage[];
  }> {
    return request.get(`/chat/shared/${shareId}`, { password });
  },

  /**
   * 取消分享会话
   */
  unshareSession(sessionId: string): Promise<void> {
    return request.delete(`/chat/sessions/${sessionId}/share`);
  },

  /**
   * 获取会话模板
   */
  getSessionTemplates(): Promise<
    Array<{
      id: string;
      name: string;
      description: string;
      personaId: string;
      initialMessages: Array<{
        role: "user" | "assistant";
        content: string;
      }>;
      tags: string[];
      category: string;
    }>
  > {
    return request.get("/chat/templates");
  },

  /**
   * 从模板创建会话
   */
  createSessionFromTemplate(
    templateId: string,
    customTitle?: string,
  ): Promise<ChatSession> {
    return request.post(
      "/chat/sessions/from-template",
      {
        templateId,
        customTitle,
      },
      {
        showLoading: true,
        loadingText: "创建会话中...",
      },
    );
  },

  /**
   * 保存会话为模板
   */
  saveSessionAsTemplate(
    sessionId: string,
    data: {
      name: string;
      description: string;
      category: string;
      includeMessages?: boolean;
    },
  ): Promise<void> {
    return request.post(`/chat/sessions/${sessionId}/save-as-template`, data, {
      showLoading: true,
      loadingText: "保存中...",
    });
  },

  /**
   * 获取推荐会话
   */
  getRecommendedSessions(): Promise<
    Array<{
      id: string;
      title: string;
      description: string;
      personaName: string;
      tags: string[];
      popularity: number;
    }>
  > {
    return request.get("/chat/recommendations");
  },

  /**
   * 获取热门话题
   */
  getTrendingTopics(): Promise<
    Array<{
      topic: string;
      count: number;
      growth: number;
    }>
  > {
    return request.get("/chat/trending-topics");
  },

  /**
   * 获取使用统计
   */
  getUsageStats(period: "day" | "week" | "month" = "week"): Promise<{
    totalSessions: number;
    totalMessages: number;
    totalTokens: number;
    averageSessionLength: number;
    mostUsedPersona: string;
    dailyStats: Array<{
      date: string;
      sessions: number;
      messages: number;
      tokens: number;
    }>;
  }> {
    return request.get("/chat/usage-stats", { period });
  },
};
